<script src="/lib/jquery-2.1.4.js"></script>
<script src="/lib/fastclick.js"></script>
<script>
  /**$(function() {
    FastClick.attach(document.body);
  });**/
    var code = <%if(typeof(code)!='undefined'){%>'<%=code%>'<%}else{%>''<%}%>;
    var isDev = <%if(typeof(isDev)!='undefined'){%>'<%=isDev%>'<%}else{%>true<%}%>;
    isDev = isDev === 'true' ;
    var isNotice = <%if(typeof(isNotice)!='undefined'){%>'<%=isNotice%>'<%}else{%>true<%}%>;
    isNotice = isNotice === 'true' ;
</script>
<script src="/lib/jquery-weui.js"></script>
<script src="/lib/template-web.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script src="/lib/common.js"></script>
<script>
    
    //$.get('/log',{info:'code => ' + code});
    //$.get('/log',{info:'isDev => ' + isDev});
    //$.get('/log',{info:'getCookie(token) => ' + getCookie('token')});
    var token = '<%=locals.token%>';
    //支付相关的准备......
    function onBridgeReady(){
      WeixinJSBridge.call('hideToolbar');
    }
    if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    }else{
        onBridgeReady();
    }
    var jsUrlHelper = {
      getUrlParam : function(url, ref) {
        var str = "";
        // 如果不包括此参数
        if (url.indexOf(ref) == -1)
          return "";
        str = url.substr(url.indexOf('?') + 1);
        arr = str.split('&');
        for (i in arr) {
          var paired = arr[i].split('=');
          if (paired[0] == ref) {
            return paired[1];
          }
        }
        return "";
      },
      putUrlParam : function(url, ref, value) {
        // 如果没有参数
        if (url.indexOf('?') == -1)
          return url + "?" + ref + "=" + value;
        // 如果不包括此参数
        if (url.indexOf(ref) == -1)
          return url + "&" + ref + "=" + value;
        var arr_url = url.split('?');
        var base = arr_url[0];
        var arr_param = arr_url[1].split('&');
        for (i = 0; i < arr_param.length; i++) {
          var paired = arr_param[i].split('=');
          if (paired[0] == ref) {
            paired[1] = value;
            arr_param[i] = paired.join('=');
            break;
          }
        }
        return base + "?" + arr_param.join('&');
      },
      delUrlParam : function(url, ref) {
        // 如果不包括此参数
        if (url.indexOf(ref) == -1)
          return url;
        var arr_url = url.split('?');
        var base = arr_url[0];
        var arr_param = arr_url[1].split('&');
        var index = -1;
        for (i = 0; i < arr_param.length; i++) {
          var paired = arr_param[i].split('=');
          if (paired[0] == ref) {
            index = i;
            break;
          }
        }
        if (index == -1) {
          return url;
        } else {
          arr_param.splice(index, 1);
          return base + "?" + arr_param.join('&');
        }
      }
    };
    //***********************************************************************
    
    //微信小程序
    if(token!='' && token != getCookie('token')){
      $.post('/antique/api/sysUser/query_my_info',{
        token:token
      },function(result){
        var data = result.data;
        var name = data.name;
        var photo = data.photo;
        var userId = data.id;
        var openId = data.openIdS;
        setCookie('name',name,24 * 30);
        setCookie('photo',photo,2);
        setCookie('userId',userId,2);
        setCookie('openId',openId,2);
        setCookie('token',token,2);
      });
    } else if(!getCookie('token') && (typeof(code)!='undefined' && code!='')){
      $.ajaxSettings.async = false;
      $.post('/antique/api/wxApi/access_token',{
        code:code
      },function(result){
        //$.get('/log',{info:'result => ' + JSON.stringify(result)});
        var openId = result.data.openid;
        var access_token = result.data.access_token;
        setCookie('access_token_expireTime',(new Date()).valueOf() + (60 * 60 * 2 * 1000) ,2);
        setCookie('access_token',access_token,2);
        setCookie('refresh_token',result.data.refresh_token,2);
        $.post('/antique/api/wxApi/userinfo',{
          access_token:access_token,
          openid:openId
        },function(result){
          var unionid = result.data.unionid;
          setCookie('unionid',unionid,2);
          setCookie('photo',result.data.headimgurl,2);
          setCookie('name',result.data.nickname,2);
          //通过用户名和openId创建用户或取得用户信息
          $.post('/antique/api/sysUser/regist_user',{
            openIdP:openId,
            name:result.data.nickname,
            unionId:unionid,
            photo:result.data.headimgurl,
            cityName:result.data.province,
            areaName:result.data.city
          },function(data){
            setCookie('userId',data.data.id,2);
            $.post('/antique/api/token/create_token',{
              unionId:unionid,
              password:data.data.password
            },function(result){
              //保存token过期时间，在过期前把token刷新一次
              setCookie('expireTime',result.data.expireTime,2);
              //把token写入cookie中一个小时
              setCookie('token',result.data.token,2);
            });
          });
        });
      });
      $.ajaxSettings.async = true;
    }
    //如果token和code都没有就跳转去授权
    else if (!getCookie('token') && (typeof(code)=='undefined' || code=='')){
      //$.get('/log',{info:'no token and no code!'});
      if(!isDev && typeof(isDev) != 'undefined' && isDev !== '' && isDev != 'false'){
        var newurl = jsUrlHelper.delUrlParam(window.location.href,'code');
        newurl = jsUrlHelper.delUrlParam(newurl,'state');
        if(newurl.split('?')[1] == ''){
          newurl = newurl.replace('?','');
        }
        //console.log('newurl => ' + newurl);
        window.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx99b0f958a8d5fd59&redirect_uri=' + newurl + '&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect');
      } else {        
        //$.get('/log',{info:'goto harrydong user!'});
        //**********************************************测试代码开始***************************************************************************************
        setCookie('photo','http://thirdwx.qlogo.cn/mmopen/vi_32/1bImQaoCiaicFYrsk1THaSL5hbJHB1cOtc2JeON8deNt7c8sQ3zH6cDxCuBLZr3M1DE1hJZNrcOUbibIwNvQPtiaQg/132',2);
        setCookie('name','harry.dong董恒',2);
        setCookie('unionid','o4owA1E2jA1AQBAA9zQ0rMDA3g6U',2);
        $.post('/antique/api/sysUser/regist_user',{
          openIdP:'o8HCg59Zi7ohuU14DTbSanSgr27s',
          name:'harry.dong董恒',
          unionId:'o4owA1E2jA1AQBAA9zQ0rMDA3g6U',
          photo:'http://thirdwx.qlogo.cn/mmopen/vi_32/1bImQaoCiaicFYrsk1THaSL5hbJHB1cOtc2JeON8deNt7c8sQ3zH6cDxCuBLZr3M1DE1hJZNrcOUbibIwNvQPtiaQg/132',
          areaName:'500106'
        },function(data){
          setCookie('userId',data.data.id,24 * 30);
          $.post('/antique/api/token/create_token',{
            unionId:'o4owA1E2jA1AQBAA9zQ0rMDA3g6U',
            password:data.data.password
          },function(result){
            //保存token过期时间，在过期前把token刷新一次
            setCookie('expireTime',result.data.expireTime,2);
            //把token写入cookie中一个小时
            setCookie('token',result.data.token,2);
          });
        });
      }
      //**********************************************测试代码结束***************************************************************************************
    }
    //如果token和expireTime都存在查看token是否要过期了
    if(getCookie('token') && getCookie('expireTime')){
      //如果过期就刷新token
      if(parseInt(getCookie('expireTime')) < (new Date()).valueOf() - 30 * 60 * 1000){
        $.post('/antique/api/token/refresh_token',{
          token:getCookie('token')
        },function(result){
          //保存token过期时间，在过期前把token刷新一次
          setCookie('expireTime',result.data.expireTime,2);
          //把token写入cookie中一个小时
          setCookie('token',result.data.token,2);
        });
      }
    }
    //如果access_token_expireTime和refresh_token都存在查看token是否要过期了
    if(getCookie('access_token_expireTime') && getCookie('refresh_token')){
      //如果过期就刷新token
      if(parseInt(getCookie('access_token_expireTime')) < (new Date()).valueOf() - 30 * 60 * 1000){
        $.post('/antique/api/wxApi/refresh_token',{
          refresh_token:getCookie('refresh_token')
        },function(result){
          setCookie('access_token_expireTime',(new Date()).valueOf() + (60 * 60 * 2 * 1000) ,2);
          setCookie('refresh_token',result.data.refresh_token,2);
        });
      }
    }
    addUrlInfo(window.location.href);
    function addUrlInfo(url){
        var gjzxUrlsStr = getCookie('gjzx_urls_str');
        var gjzxUrls = [];
        if (gjzxUrlsStr){
            gjzxUrls = JSON.parse(gjzxUrlsStr);
        }
        for(var i = 0;i<gjzxUrls.length;i++){
          if (gjzxUrls[i] == url){
            gjzxUrls.splice(i, 1);
          }
        }
        if (gjzxUrls.length > 4){
            gjzxUrls.shift();
        }
        gjzxUrls.push(url);
        setCookie('gjzx_urls_str',JSON.stringify(gjzxUrls),-1);
    }

    if(isNotice){
      debugger
      delCookie('gjzx_urls_str');
    }

    function getLastUrl(){
        var gjzxUrlsStr = getCookie('gjzx_urls_str');
        var gjzxUrls = [];
        if (gjzxUrlsStr){
            gjzxUrls = JSON.parse(gjzxUrlsStr);
        }
        if (gjzxUrls.length == 0){
            return false;
        } else {
            return gjzxUrls[gjzxUrls.length - 2];
        }
    }

    function popLastUrl(){
      var gjzxUrlsStr = getCookie('gjzx_urls_str');
      var gjzxUrls = [];
      if (gjzxUrlsStr){
        gjzxUrls = JSON.parse(gjzxUrlsStr);
      }
      if (gjzxUrls.length > 0){
        gjzxUrls.pop();
        setCookie('gjzx_urls_str',JSON.stringify(gjzxUrls),-1);
      }
    }
</script>